package  subumbo.audio.driver
{
	import __AS3__.vec.Vector;
	
	import flash.events.SampleDataEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.utils.setTimeout;
	
	import subumbo.audio.core.AudioEngine;	


	public class AudioDriver 
	{
		static public const SIZE: int = 3072;
		
		private const BUFFER: Vector.<Vector.<Number>> = new Vector.<Vector.<Number>>( 2, true );
		
		private const sound: Sound = new Sound();
		
		private var _channel: SoundChannel;

		private var _engine: AudioEngine;
		
		private var _silenceWriteCounter:int = 0;

		public function AudioDriver( engine: AudioEngine )
		{
			_engine = engine;
			
			//-- Stereo (2 channels)
			BUFFER[0] = new Vector.<Number>( SIZE, true );
			BUFFER[1] = new Vector.<Number>( SIZE, true );
			
			sound.addEventListener( SampleDataEvent.SAMPLE_DATA, sampleData );
			
			setTimeout(play,5000);
		}
		
		public function get leftPeak(): Number
		{
			return _channel == null ? 0.0 : _channel.leftPeak;
		}
		
		public function get rightPeak(): Number
		{
			return _channel == null ? 0.0 : _channel.rightPeak;
		}
		
		public function play(): void
		{
			if(_channel) return
			_channel =  sound.play();
		}
		
		public function stop():void
		{
			_channel.stop();
		}

		private function sampleData( event: SampleDataEvent ): void
		{
			_engine.process( BUFFER );

			var le: Vector.<Number> = BUFFER[0]; // left channel
			var ri: Vector.<Number> = BUFFER[1]; // right channel
			
			var i: int = 0;
			var n: int = SIZE;
			
			for( ; i < n ; ++i )
			{
				//trace(le[i])
				event.data.writeFloat( le[i] );
				event.data.writeFloat( ri[i] );
			}
		}
		
		public function writeSilence():void
		{
			_channel.stop();
			var i: int = 0;
			for( ; i < SIZE ; ++i )
			{
				BUFFER[0][i] = 0.0;
				BUFFER[1][i] = 0.0;
			}
			if(_silenceWriteCounter == 5)
			{	
				_silenceWriteCounter = 0;		
				_channel = sound.play();
				return;
			}
			_silenceWriteCounter++;
			writeSilence();
			
		}
	}
}
